<template>
  <div class="did-h">
    <!-- <div style="width: 80%; height: 100px; margin: auto; margin-top: 30px">
      <el-input placeholder="请输入士兵号/装备号" v-model="input3" class="input-with-select">
        <el-select v-model="select" slot="prepend" placeholder="请选择">
          <el-option label="DID" value="1"></el-option>
          <el-option label="士兵号/装备号" value="2"></el-option>
          <el-option label="用户名/装备名" value="3"></el-option>
          <el-option label="部门" value="4"></el-option>
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="filterTableData"></el-button>
      </el-input>
    </div> -->

    <div>
      <!-- 表格 -->
      <el-table :data="pagedTableData" :current-page="currentPage" :page-size="pageSize" ref="multipleTable" style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }" @row-click="handleRowClick">
        <el-table-column prop="did" label="DID" width="400x" align="center"></el-table-column>
        <el-table-column prop="number" label="士兵号" width="150x" align="center"></el-table-column>
        <el-table-column prop="name" label="用户名" align="center"></el-table-column>
        <el-table-column prop="department" label="部门" width="100px" align="center"></el-table-column>
        <el-table-column prop="publicKey" label="公钥" width="500px" align="center"></el-table-column>
        <el-table-column prop="createDate" label="注册时间" sortable show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="operate" label="角色操作" align="center">
          <template scope="scope">
            <el-button type="primary" icon="el-icon-copy-document" size="small" @click="goToManageRole(scope.row)">管理角色</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="personnel" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-if="scope.row">
              <el-button @click="handleClick(scope.row)" type="text" size="small">冻结</el-button>
              <el-button @click="handleReject(scope.row)" type="text" size="small">解冻</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="handleCurrentPageChange" style="margin-top: 30px"></el-pagination>
    </div>
  </div>
</template>

<script>
import { MessageBox } from 'element-ui';
import axios from 'axios';

export default {
  data() {
    return {
      input3: '',
      select: '',
      currentPage: 1,
      scope: { row: null },
      pageSize: 10,
      total: 0,
      tableData: [], // 所有数据
      pagedTableData: [], // 分页后的数据
      showDialog: false,
      selectedRow: null,
      value1: true,
      value2: true,
      //搜索框
      searchInput: '',
    };
  },
  mounted() {
    // 初始化数据
    this.showChainData(1, 1, '', 1);
  },
  methods: {
    computed: {
      filteredData() {
        const searchTerm = this.searchInput.trim();
        if (searchTerm !== '') {
          return this.tableData.filter((item) => item.name.includes(searchTerm));
        } else {
          return this.tableData;
        }
      },
    },
    //搜索框
    fetchData() {
      const searchTerm = this.searchInput.trim();
      if (searchTerm !== '') {
        this.pagedTableData = this.pagedTableData.filter((item) => item.name.includes(searchTerm));
      } else {
        this.pagedTableData = this.pagedTableData;
      }
    },
    async Freeze(did, number) {
      let formData = new FormData();
      formData.append('did', did);
      formData.append('number', number);
      console.log(did);
      let res = await this.$http.post(this.$api.userIdentity.Freeze, formData);
      if (res.code === 200) {
        this.data = res;
      }
    },
    handleClick(row) {
      this.form = Object.assign({}, row);
      this.Freeze(row.did, row.number);
    },
    handleReject(row) {
      this.form = Object.assign({}, row);
      this.Thaw(row.did, row.number);
    },
    async Thaw(did, number) {
      let formData = new FormData();
      formData.append('did', did);
      formData.append('number', number);
      let res = await this.$http.post(this.$api.userIdentity.Thaw, formData);
      if (res.code === 200) {
        this.data = res;
      }
    },

    async showChainData(did, datatype, data, pageNum) {
      let formData = new FormData();
      formData.append('did', did);
      formData.append('datatype', datatype);
      formData.append('number', data);
      formData.append('pageNum', pageNum);
      formData.append('pageSize', this.pageSize);
      try {
        let res = await this.$http.post(this.$api.userIdentity.showChainData, formData);
        if (res.status === 200) {
          this.pagedTableData = res.data.records; // 请求成功后将res.data赋值给tableData
          this.total = res.data.total;
          console.log(res.data);
        }
      } catch (error) {
        console.error(error);
      }
    },
    async handleDocumentClick(documents) {
      try {
        // 发起异步请求获取证件文件的二进制数据
        const response = await this.$http.get(documents, { responseType: 'blob' });

        // 创建一个 Blob 对象，表示证件文件的二进制数据
        const blob = new Blob([response.data], { type: 'application/octet-stream' });

        // 生成临时下载链接
        const url = URL.createObjectURL(blob);

        // 创建一个隐藏的<a>元素来模拟点击下载操作
        const link = document.createElement('a');
        link.href = url;
        link.download = 'document.pdf'; // 设置默认下载文件名
        link.style.display = 'none';

        // 将<a>元素添加到文档中并模拟点击
        document.body.appendChild(link);
        link.click();

        // 下载完成后，撤销临时下载链接
        URL.revokeObjectURL(url);
      } catch (error) {
        console.error('下载证件文件失败：', error);
        // 在下载失败时，您可以添加适当的错误处理逻辑
      }
    },

    filterTableData() {
      if (this.input3.trim() === '') {
        // 如果搜索关键字为空，将过滤后的数据设置为全部数据
        this.filteredTableData = this.tableData;
      } else {
        const keyword = this.input3.trim().toLowerCase();
        const filteredData = this.tableData.filter((item) => {
          // 根据选择器的值确定要搜索的字段
          let field;
          switch (this.select) {
            case '1':
              field = 'did';
              break;
            case '2':
              field = 'number';
              break;
            case '3':
              field = 'name';
              break;
            case '4':
              field = 'department';
              break;
            default:
              field = 'did'; // 默认使用DID字段
          }
          // 根据关键字和字段进行匹配
          return item[field].toLowerCase().includes(keyword);
        });
        // 更新过滤后的数据
        this.filteredTableData = filteredData;
      }
      // 更新分页数据
      this.showChainData(1, 1, this.input3.trim(), 1); //
      this.updatePagedTableData();
    },

    updatePagedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.pagedTableData = this.filteredTableData.slice(start, end);
    },
    handleCurrentPageChange(currentPage) {
      this.currentPage = currentPage;
      this.showChainData(1, 1, this.input3.trim(), this.currentPage);
    },
    handleRowClick(row) {
      console.log(row);
      this.row = row;
    },
    goToManageRole(row) {
      console.log(row);
      if (row && row.did && row.number) {
        console.log(row);
        const dynamicId = row.did;
        const dynamicNum = row.number;
        this.$router.push({ path: '/Manager', query: { id: dynamicId, num: dynamicNum } });
      } else {
        console.error("Invalid row object or missing 'did' and 'number' properties.");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.did-content {
  margin-top: 10%;

  h1 {
    color: #666666;
    width: 320px;
    margin: 0 auto;
  }
}

.did-button {
  width: 100px;
  margin: 0 auto;
  margin-top: 20px;
}

.m-a0 {
  margin: 0 auto;
}

.black-h {
  height: 50%;
}

.black-height {
  height: calc(50% - 90px);
}

.nodata {
  margin-top: 10%;
}

.did-width {
  width: 500px;
  margin: 0 auto;
}

.text-c {
  text-align: center;
  font-size: 20px;
  font-weight: 600;
}
</style>
